<?php

class CategoryController extends Controller
{
	public $layout='application.modules.admin.views.layouts.default';

	public static $catename;
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider = array();
		
	    $criteria = new CDbCriteria(
            array(
//                'condition'=>'cate_type=:cate_type',
                'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',
            //    'params'=>array(
//                    ':cate_type'=>isset($_GET['type'])?$_GET['type']:''
//                )
            )
        );
        
        $items = Category::model()->findAll($criteria);
        foreach ($items as $item)
        {
        	$dataProvider[] = $item->attributes;
        }
        $dataProvider = Category::model()->getChildrenArray($dataProvider);

        
        $perpage = 10;
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:1;
        $offset = 10;
        $start = (3 - 1) * $offset;
        $pagecount = (int)count($dataProvider)/$offset;
        $dataProvider = array_slice($dataProvider, $start,$offset);
        
        $pageInfo = array(
        	'pageCount'=>$pagecount,
        	'offset'=>$offset
        );

        echo "<pre>";
        var_dump($dataProvider);
        echo "</pre>";
        
//		$dataProvider=new CActiveDataProvider('Category',array(        
//            'criteria'=>$criteria
//        ));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
			'pageInfo'=>$pageInfo
		));
	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
		/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','view','generatethumbnail','hideresult','items','create','createremote','remotecreate2','update','quickupdate','findparent','thumbnails','children','getcontenttype','categories'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','deleteremote'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}
	
	public function actionGetContentType()
	{
		if(isset($_GET['id']))
		{
			$model = $this->loadModel();
			
			if ($model)
				echo $model->cate_contype;
		}
	}
	
	/**
	 * Dispalys all category model
	 */
	public function actionItems()
	{
		$this->layout='application.modules.admin.views.layouts.blank';
		
		$criteria = new CDbCriteria();
		
		if(isset($_GET['type']))
		{
			$criteria->condition = 'cate_type = '.$_GET['type'];
		}
		
		$category = Category::model()->findAll($criteria);
		

		$items = Category::model()->getChildrenObject($category, 0, 0);	
		
        foreach ($items as $item)
        {
        	$dataProvider[] = $item->attributes;
        }
        $dataProvider = Category::model()->getChildrenArray($dataProvider);


        
        $perpage = 10;
        $page = isset($_REQUEST['page'])?$_REQUEST['page']:1;
        $offset = 10;
        $start = ($page - 1) * $offset;
        $count = count($dataProvider);
        $pagecount = (int)count($dataProvider)/$offset;
        $dataProvider = array_slice($dataProvider, $start,$offset);
        
        $pageInfo = array(
        	'pageCount'=>$pagecount,
        	'itemsCount'=>$count,
        	'page'=>$page,
        	'offset'=>$offset
        );    
            
//        UtilTools::dump($pageInfo);
//        UtilTools::dump($dataProvider);
//        die();
		
//        $criteria = new CDbCriteria(
//            array(
//                'condition'=>'cate_type=:cate_type AND cate_pid != 0',
//                'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',
//                'params'=>array(
//                    ':cate_type'=>isset($_GET['type'])?$_GET['type']:''
//                )
//            )
//        );
//
//		$dataProvider=new CActiveDataProvider('Category',array(
//            'criteria'=>$criteria,
//            'pagination'=>array(
//                'pageSize'=>12
//            )
//        ));
		$this->render('items',array(
			'dataProvider'=>$dataProvider,
			'pageInfo'=>$pageInfo
		));

        
        
//		$this->render('items',array(
//			'cate'=>$cateModel
//		));
	}
	
	public function actionHideResult()
	{
		$this->layout='application.modules.admin.views.layouts.blank';
		
		$criteria = new CDbCriteria();
		
		if(isset($_GET['type']))
		{
			$criteria->condition = 'cate_type = '.$_GET['type'];
		}
		
		//start
		//以下为cheery模板完成学校所增加
		elseif (isset($_GET['cid']))
		{
			$model = Category::model()->findByPk($_GET['cid']);
			$criteria->condition = 'cate_type = '.$model->cate_type;
		}	
			
		//end
		$category = Category::model()->findAll($criteria);
		$items = Category::model()->getChildrenObject($category, 0, 0);	
		
        foreach ($items as $item)
        {
        	$dataProvider[] = $item->attributes;
        }
        $dataProvider = Category::model()->getChildrenArray($dataProvider);

//        //
//        UtilTools::dump($dataProvider);

        
        $perpage = 10;
        $page = (int)isset($_REQUEST['page'])?$_REQUEST['page']:0;
        $offset = 10;
        
	    if(isset($_REQUEST['catename'])&&$_REQUEST['catename']!='')
        {
//        	echo $_REQUEST['catename'];
        	
        	$catename = $_REQUEST['catename'];
			$itemNum = UtilTools::multiArraySearch($catename, $dataProvider);
//			echo $itemNum;
			$page = round($itemNum/$offset);	
//			echo $page;
        }
        
        
        $start = $page * $offset;
        $count = count($dataProvider);
        $pagecount = (int)count($dataProvider)/$offset;
        
        $offset2 = ($count-$start < $offset)?($count-$start):$offset;
        
//        echo $offset.'-'.$start.'-'.($count-$start);
        $dataProvider = array_slice($dataProvider, $start,$offset2);
        
        $pageInfo = array(
        	'pageCount'=>$pagecount,
        	'itemsCount'=>$count,
        	'page'=>$page,
        	'offset'=>$offset
        );
        
        $this->render('hideresult',array(
        	'dataProvider'=>$dataProvider,
        	'pageInfo'=>$pageInfo
        ));		
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{

        $criteria = new CDbCriteria(
            array(
                'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',

            )
        );

		$dataProvider=new CActiveDataProvider('Category',array(
            'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>12
            )
        ));
	
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
 		$this->performAjaxValidation($model);
		

 		if(isset($_POST['cate_pid']))
		{
			$model->cate_order = isset($_POST['cate_order'])?$_POST['cate_order']:500;
			$model->cate_des = isset($_POST['cate_des'])?$_POST['cate_des']:"无";
			$model->cate_name = $_POST['cate_name'];
			$model->cate_type = $_POST['cate_type'];
			$model->cate_pid = isset($_POST['cate_pid'])?$_POST['cate_pid']:0;
			$model->cate_recommend = $_POST['cate_recommend'];
			$model->cate_link = $_POST['cate_link'];
			$model->cate_contype = $_POST['cate_contype'];
			
//			var_dump($model->attributes);
			
			if($model->save()){
				$this->redirect(array('items'));
//				die("ok");
			}else{
				die("false");
			}
			
		}

		$this->render('create',array(
			'model'=>$model,
			'dataProvider'=>$dataProvider
		));
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreateRemote()
	{
		$this->blackLayout();
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
//		var_dump($_POST);
		
		if(isset($_POST['cate_pid']))
		{
			$model->cate_order = isset($_POST['cate_order'])?$_POST['cate_order']:500;
			$model->cate_des = isset($_POST['cate_des'])?$_POST['cate_des']:"无";
			$model->cate_name = $_POST['cate_name'];
//			$model->cate_type = $_POST['cate_type'];
			$model->cate_pid = $_POST['cate_pid'];
			$model->cate_contype = Category::CONTENT_STORY;
			$model->cate_recommend = Category::CATEGORY_RECOMMEND_CANCEL;
			
			//以下为scholl主题所增加内容
			$cateModel = Category::model()->findByPk($_POST['cate_pid']);
			
			if($cateModel)
				$model->cate_type = $cateModel->cate_type;
			
//			var_dump($model->attributes);
//			die();
			if($model->save()){
				//Category add
				if(isset($_POST['self'])){
					$this->render('_view',array(
						'data'=>$model
					));					
				}
				// Article category add
				else{
					echo '<li><input type="checkbox" value="'.$model->cate_id.'" checked="checked" />&nbsp;'.$model->cate_name.'</li>';					
				}
			}else{
				die("Error");
			}
		}
	}	
	
	/**
	 * @see http://www.rewrite.com/admin/video/create.shtml
	 * @method actionRemoteCreate2
	 * @todo 此方法如上，用于增加类别,但此方法并不有检查所增加的类别是否已经存在
	 * @return $this->actionChildren
	 * 
	 * 
	 */
	public function actionRemoteCreate2()
	{
		$this->blackLayout();
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
//		var_dump($_GET);
//		die();
		
		if(isset($_GET['cate_pid']))
		{
			
			$model->cate_order = isset($_GET['cate_order'])?$_GET['cate_order']:500;
			$model->cate_des = isset($_GET['cate_des'])?$_GET['cate_des']:"无";
			$model->cate_name = $_GET['cate_name'];
			$model->cate_type = $_GET['cate_type'];
			$model->cate_pid = $_GET['cate_pid'];
//			echo json_encode($model->attributes);
//			die();
			if($model->save()){
				//Category add
				$this->actionChildren($model->cate_type);

			}else{
				die("Error");
			}
		}		
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{

		$this->baseLayout();
		
		$category = Category::model()->findAll();
		$cateModel = Category::model()->getChildrenObject($category, 0, 0);			
		
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
		
		if(isset($_POST['Category']))
		{

			
			
//			var_dump($model->attributes);
			
//			$count = Category::model()->count('cate_name = :cate_name',array(':cate_name'=>$_POST['Category']['cate_name']));
//            
//            if($count > 0)
//            {
//                die("exists");
//            }
            
            $model->attributes=$_POST['Category'];   

            //修改分类更新时未更新所属类型的bug
            
            $pid = $model->cate_pid;
            
            $parent = Category::model()->findByPk($pid);
            
			if($parent){
				$model->cate_type = $parent->cate_type;
			}
            
            
            $model->cate_des = $_POST['Category']['cate_des'];

//            var_dump($model->attributes);
//            die();
		
//            try {
//            	$model->save();
//            }
//            catch (CException $e)
//            {
//            	$e->getMessage();
//            }
			if($model->save()){
				die("ok");
			}else{
				die("fail");
			}
		}
		
		$this->render('update',array(
			'model'=>$model,
			'cateModel'=>$cateModel
		));
	}
	
	public function actionQuickUpdate()
	{
		$model = $this->loadModel();

		$model->cate_name = $_GET['name'];
		$model->cate_contype = $_GET['contype'];
        
//        var_dump($_GET);
//        
//        var_dump($model->attributes);
//        die();
        try
        {
            if($model->save())
                echo 'ok';
        }
        catch(CException $e)
        {
            echo $e->getMessage();
        }
        

	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			echo $this->loadModel()->delete();
			
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDeleteRemote()
	{
//		var_dump($_REQUEST);
//		die();
		if(Yii::app()->request->isPostRequest)
		{
			
			// we only allow deletion via POST request
			try
			{
				if($this->loadModel()->delete())
					echo 'ok';
			}
			catch(CException $e)
			{
				echo $e->getMessage();	
			}			
			
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionDeleteBatch()
	{
		
//		var_dump($_REQUEST);
//		die();
		$ids = $_GET['ids'];
		
		$ids = explode(',', $ids);
		foreach($ids as $id)
		{
			$model = Category::model()->findbyPk($id);
			if($model!=null)
			{
				$model->delete();
			}			
		}
		echo "ok";
	}
	/**
	 * generate category thumbnail
	 */
	public function actionGenerateThumbnail()
	{
//		var_dump($_REQUEST);
//		$url = $_REQUEST['url'];
//		echo Yii::app()->request->hostInfo.str_replace('_thumb', '', $url);
//
//		die();
		if(isset($_REQUEST['id']))
		{
			$id = $_REQUEST['id'];
			$url = $_REQUEST['url'];
			$url = Yii::app()->request->hostInfo.str_replace('_thumb', '', $url);
			$filepath = Yii::app()->params['uploadCategoryPath'];
			$desPath = '.'.$filepath.Category::getCategoryName($id);
		
			$destination = '.'.$filepath.$this->getCategoryName($id).'.jpg';
			$thumb_destination = '.'.$filepath.$this->getCategoryName($id).'_thumb.jpg';
			
//			
//			echo $url;
//
//			echo $thumb_destination;
			if(!file_exists($destination))
				File::createFolder(dirname($destination));
				
//			if(file_exists($url)){
//				echo "OK file exists";
//			}else{
//				echo "Fail";
//			}
//			die();
			
			$data = file_get_contents($url);
//			file_put_contents($destination, $data);
//			die();
			if(file_put_contents($destination, $data)){
				Category::model()->generateImage($destination, $desPath);
				$t = new ThumbHandler();
				$t->setSrcImg($destination);
			
				$t->setImgDisplayQuality(90);
				$t->setDstImg($thumb_destination);
				$t->setDstImgBorder(0,"#dddddd");
				$t->createImg(500,250);
		
		//		Yii::app()->thumb->setThumbsDirectory($filepath.'2011/01/30/');
		// 
		//		Yii::app()->thumb
		//		->load($destination)
		//		->crop(0,0,250,160)
		//		->save($thumb_destination, "GIF");
				
				
				$t = new ThumbHandler();
				$t->setSrcImg($thumb_destination);
				
				$t->setMaskImg("./images/logo.gif");
				$t->setMaskPosition(4);
				$t->setMaskImgPct(30);
			
				$t->setCutType(2);//指明为手工裁切
				$t->setSrcCutPosition(0, 0);// 源图起点坐标
				$t->setRectangleCut(242, 140);// 裁切尺寸
				$t->setImgDisplayQuality(90);
				$t->setDstImg($thumb_destination);
				$t->setDstImgBorder(4,"#dddddd");
				if($t->createImg(250,140))
				{
					echo "Category folder settting success";
				}
			}else{
				echo "File save not success!";
			}

		}
		
	}
	
	//get all Thumbnails by file_pid
	public function actionThumbnails()
	{
		$this->layout = '//layouts/blank';
		$thumbnails = Gallery::model()->findAll('file_type=:file_type AND file_pid = :file_pid',array(':file_type'=>Category::CATEGORY_GALLERY,':file_pid'=>$_GET['id']));
		$this->render('thumbnails',array(
			'thumbnails'=>$thumbnails
		));

	}
	
	public function actionCategories()
	{
		echo json_encode(Category::model()->getArticleCategoryDropdownList());
		
		die();
	}
	
	
	
	
	/**
	 * @method actionChildren()
	 * @todo Generate Options list
	 */
	public function actionChildren($cid = null)
	{
		if(isset($_GET['cid']))
			$arr = Category::model()->getCategoryDropdownList($_GET['cid']);
		
		echo json_encode($arr);
		die();

//		foreach ($arr as $k=>$v){
//			echo "$k=>$v";
//		}
		
//		die();
//		$option = '<option value="0">无</option>';
		$option = "";
		foreach ($arr as $k => $v){
			$option .= '<option vaule="'.$k.'"';
			if($k == $_POST['id']){
				$option .= ' selected = "selected"';
			}
			$option .= '>';
			
			$option .= $v.'</option>';
		}
		echo $option;
//		var_dump($arr);

	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Category('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Category']))
			$model->attributes=$_GET['Category'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Category::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 
	 * @modify 增加一个参数$cate_type
	 * @param $pid
	 * @param $cate_type
	 */
	public function dropDownList($pid=0,$cate_type = Category::CATEGORY_STORY)
	{
		$cate = Category::model()->findAll('cate_type = :cate_type',array(':cate_type'=>$cate_type));
		$cate = Category::model()->toArray($cate);
		$arr = Category::model()->getChildren($cate, $pid, 0);
		$arr = Category::model()->dropListArray($arr);
		return $arr;
	}
	

	
     public function getExt($filePath){  
         $arr=pathinfo($filePath);  
         return strtolower($arr['extension']);  
     }
	
	public function getCategoryName($id)
	{
		return $this->findParent($id).$id;
	}
	
	public function findParent($id,&$catename=""){
		if(isset($id))
		{
			$model=Category::model()->findbyPk($id);
			if($model->cate_pid != 0)
			{				
				$catename = $model->cate_pid.$catename;
				$this->findParent($model->cate_pid,$catename);
			}
			return $catename;
		}
	}	
	/**
	 * 说明：由于每一个视频所属多个分类，以下将分类统计出所有子类下图片所点用空间和分类下图片数目
	 * Enter description here ...
	 * @var unknown_type
	 */
	public function getCategories($limit = 9){

		$category = Category::model()->findAll(array(
			'condition'=>'cate_type = '.Category::CATEGORY_GALLERY,
			'limit'=>isset($limit)?$limit:'',
			'order'=>'cate_id DESC'
		));
//		
		$result = array();
//		echo "<pre>";
		$i = 0;
		foreach ($category as $data){
//			var_dump($data->attributes);
			$result[] = $data->attributes;
			
			//以下统计出每个分类下的图片总数
			$gallery = Gallery::model()->findAll(
				'file_type = :file_type',
				array(
					':file_type'=>Category::CATEGORY_GALLERY
				)
			);
//			echo "<pre>";
			if(count($gallery) > 0){
				$galleryTemp = array();
				$result[$i]['cate_count'] = 0;
				$result[$i]['cate_size'] = 0;
				foreach ($gallery as $gdata){
					$pid = $gdata->file_pid;
					$pid = explode(',', $pid);
//					var_dump($pid);/
					if(in_array($data->cate_id, $pid)){
						$galleryTemp[] = $gdata->attributes;
						//统计所有图片所占用空间大小
						$result[$i]['cate_size'] += $gdata->file_size;
					}
					
				}
//				var_dump($galleryTemp);	
				$result[$i]['cate_count'] = count($galleryTemp);
				$i++;		
			}

			

		}
				
//		var_dump($result);
		$category = json_decode(json_encode($result));
		return $category;
	}
	
	protected function blackLayout()
	{
		$this->layout='application.modules.admin.views.layouts.blank';
	}
	
	protected function baseLayout()
	{
		$this->layout='application.modules.admin.views.layouts.base';
	}
}